/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.edu.zut.jdbcpool.datasource;

import cn.edu.zut.jdbcpool.reflect.ConnectionHandler;
import cn.edu.zut.jdbcpool.util.LogUtils;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

/**
 *
 * @author jyc
 */
public class PoolDataSource extends BaseDataSource {
    
    @Override
    protected void initPool() {
        try {
            Class.forName(getDriverClassName());
            dbPool = new LinkedList<>();
            for(int i = 0; i < getInitialSize(); i ++) {
                Connection conn = DriverManager.getConnection(getUrl(), getUsername(), getPassword());
                LogUtils.info("initial pool, get connection " + i);
                dbPool.add(conn);
            }
        } catch (ClassNotFoundException | SQLException ex) {
            throw new RuntimeException("initial pool error.", ex);
        }
    }

    @Override
    protected Connection requireConnection() {
        if(dbPool.size() > 0) {
            LogUtils.info("current connection count: " + dbPool.size());
            Connection conn = dbPool.removeFirst();
            LogUtils.info("get conn from pool, left: " + dbPool.size());
            return (Connection) getConnectionProxy(conn);
        } else {
            LogUtils.warn("pool is busy!");
            return null;
        }
    }
    
    public Object getConnectionProxy(Connection conn) {
        ConnectionHandler handler = new ConnectionHandler(conn, dbPool);
        Class<?>[] interfaces = conn.getClass().getInterfaces();
        ClassLoader loader = getClass().getClassLoader();
        return Proxy.newProxyInstance(loader, interfaces, handler);
    }
}
